extends CharacterBody2D

@export var idle_state_time_interval : float = 5.0
@onready var idle_state_timer : Timer = Timer.new()
@onready var animation_tree: AnimationTree = $AnimationTree
@onready var navigation_agent_2d: NavigationAgent2D = $NavigationAgent2D

@export var min_speed : float = 5.0
@export var max_speed : float = 10.0

var current_walk_cycle : int = 0
var walk_cycle : int = 0
var min_walk_cycle : int = 3
var max_walk_cycle : int = 6

var speed : float
var in_walk_state : bool = false

func _ready() -> void:
	idle_state_timer.wait_time = idle_state_time_interval
	idle_state_timer.timeout.connect(on_idle_state_timeout)
	add_child(idle_state_timer)
	idle_state_timer.start()

func on_idle_state_timeout() -> void:
	# enter walk state
	print("timeout")
	idle_state_timer.stop()
	in_walk_state = true
	current_walk_cycle = 0
	walk_cycle = randi_range(min_walk_cycle, max_walk_cycle)
	call_deferred("character_setup")

func character_setup() -> void:
	await get_tree().physics_frame
	setup_movement_target()
	
func setup_movement_target() -> void:
	var target_position : Vector2 = NavigationServer2D.map_get_random_point(
		navigation_agent_2d.get_navigation_map(), navigation_agent_2d.navigation_layers, false)
	navigation_agent_2d.target_position = target_position
	speed = randf_range(min_speed, max_speed)

func _process(delta: float) -> void:
	if in_walk_state and current_walk_cycle == walk_cycle and navigation_agent_2d.is_navigation_finished():
		print("enter idle and start timer")
		in_walk_state = false
		idle_state_timer.start()

func _physics_process(delta: float) -> void:
	if in_walk_state and current_walk_cycle < walk_cycle:
		if navigation_agent_2d.is_navigation_finished():
			setup_movement_target()
			print(current_walk_cycle)
			current_walk_cycle += 1
			return

		var target_position : Vector2 = navigation_agent_2d.get_next_path_position()
		var direction = $".".global_position.direction_to(target_position)

		var velocity : Vector2 = direction * speed
		if navigation_agent_2d.avoidance_enabled:
			$AnimatedSprite2D.flip_h = velocity.x < 0
			navigation_agent_2d.velocity = velocity
		else:
			$".".velocity = velocity
			$".".move_and_slide()


func _on_navigation_agent_2d_velocity_computed(safe_velocity: Vector2) -> void:
	$AnimatedSprite2D.flip_h = safe_velocity.x < 0
	$".".velocity = safe_velocity
	$".".move_and_slide()
